const fs = require('fs');

class CoCoMetricDB {
    constructor(sqlite3, dbPath) {
        // 检查数据库文件是否存在
        if (!fs.existsSync(dbPath)) {
            // console.error(`Database file does not exist: ${dbPath}`);
            throw new Error(`Database file does not exist: ${dbPath}`);
        }

        // 连接数据库
        this.db_path = dbPath;
        this.db = new sqlite3.Database(dbPath, (err) => {
            if (err) {
                console.error(`An error occurred when connecting to the database: ${err.message}`);
            } else {
                // console.log(`## Open MetricDB ${this.db_path} OK!`);
            }
        });
    }

    async getEvalDetails(filters = {}) {
        // console.log(`getEvalDetails filters = `, filters);
        return new Promise((resolve, reject) => {
            let query = 'SELECT * FROM eval_match_pairs';
            const conditions = [];
            const params = [];

            if (filters.category_id) {
                conditions.push(`category_id IN (${filters.category_id.map(() => '?').join(',')})`);
                params.push(...filters.category_id);
            }

            if (filters.area) {
                conditions.push(`area IN (${filters.area.map(() => '?').join(',')})`);
                params.push(...filters.area);
            }

            if (filters.iou_threshold) {
                conditions.push(`iou_threshold IN (${filters.iou_threshold.map(() => '?').join(',')})`);
                params.push(...filters.iou_threshold);
            }

            if (conditions.length > 0) {
                query += ' WHERE ' + conditions.join(' AND ');
            }

            this.db.all(query, params, (err, rows) => {
                if (err) {
                    reject(`An error occurred during query execution: ${err.message}`);
                } else {
                    resolve(rows);
                }
            });
        });
    }

    async close() {
        return new Promise((resolve, reject) => {
            if (this.db) {
                this.db.close((err) => {
                    if (err) {
                        console.error(`## Close MetricDB ${this.db_path} Failed, Error: `, err);
                        reject(err);
                    } else {
                        // console.log(`## Close MetricDB ${this.db_path} OK!`);
                        resolve();
                    }
                });
            } else {
                resolve();
            }
        });
    }
}

module.exports = { CoCoMetricDB };
